package com.lahuan.rpc.filter;

import org.apache.dubbo.rpc.*;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Random;

/**
 * @author lfy
 */
public class CustomFilter implements Filter {

    String time = null;
    int count = 0;
    int maxCount = 10;


    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

        int rd = new Random().nextInt(10);
        int limit = 9;
        if(rd>limit){
            throw new RuntimeException("模拟权限不足异常");
        }
        //限流规则和拒绝
        check();

        return invoker.invoke(invocation);
    }
    private void check() {
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmm");
        Calendar calendar = Calendar.getInstance();
        String curTime = df.format(calendar.getTime());
        //看看是不是和之前一样的分钟
        if(curTime.equals(time)){
            if(++count >=maxCount){
                throw new RuntimeException("超过限流阈值.");
            }
        }else{
            time = curTime;
            count = 1;
        }
    }
}